<template>
  <div class="Title" :style="{ ...border, backgroundColor: style.backgroundColor }">
    <div ref="widget">
      <span>{{ config.text }}</span>
    </div>
  </div>
</template>

<script>
  import borderMixin from '@/mixins/borderMixin';
  import widgetResizeMixin from '@/mixins/widgetResizeMixin';

  export default {
    mixins: [borderMixin, widgetResizeMixin],
    props: {
      widget: {
        type: Object,
        default: () => ({})
      }
    },

    computed: {
      config() {
        return this.widget.config;
      },
      style() {
        return this.widget.style;
      }
    },

    watch: {
      // 自适应规则：
      // relative：采用flexible自适应规则
      // absolute：可自由控制宽高，但是限制高度最小为内容高度
      'style.position': function (newVal) {
        const $ele = this.$refs.widget;
        if (newVal === 'relative') {
          $ele.style.height = 'auto';
          this.widget.flexible = true;
          this.resize();
        } else {
          this.widget.flexible = false;
        }
      },
      // flexible自适应规则
      'config.text': 'resize',
      'style.fontSize': 'resize',
      'style.paddingLeft': 'resize',
      'style.paddingRight': 'resize',
      'config.bordered': 'resize',
      'style.borderWidth': 'resize',
      // 限制高度最小
      'style.width': 'resize'
      // 'style.height': 'validateHeight'
    },

    created() {
      this.style.position === 'relative' && (this.widget.flexible = true);
    },

    methods: {
      // 限制手动高度时不得低于内容高度
      validateHeight: function () {
        if (this.flexible) return;
        const borderWidth = this.config.bordered ? this.style.borderWidth : 0;
        const widgetHeight = this.$refs.widget.clientHeight + borderWidth * 2;
        if (this.style.height < widgetHeight) this.style.height = widgetHeight;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .Title {
    overflow: hidden;
    line-height: 1.2;
    text-align: justify;
    white-space: break-spaces;
    letter-spacing: 1px;
    word-break: break-all;
  }
</style>
